<!-- 通用蓝牙模块组件 -->
<template>
	<view v-show="showLog">
		<view style="text-align: center;">---- 当前蓝牙状态Log ----</view>
		<view>连接名称：{{bleInfo.deviceState == 1? bleInfo.deviceName:"未连接"}}</view>
		<view>BLEInfo：{{JSON.stringify(bleInfo)}}</view>
		<view>BLEData：{{JSON.stringify(bleData)}}</view>
	</view>
</template>

<script>
	let SUCCESS = {
		code: 0
	}
	let ERROR = function error(msg) {
		return {
			code: 1,
			msg: msg
		}
	}
	export default {
		data() {
			return {
				//获取蓝牙连接地址状态
				bleData: {
					type: Object,
					default: {
						services: [],
						serviceId: 0,
						writeCharacter: false,
						readCharacter: false,
						notifyCharacter: false,
					}

				}
			};
		},
		props: {
			//是否显示调试log
			showLog: {
				type: Boolean,
				default: false
			},
			//蓝牙核心连接信息
			bleInfo: {
				type: Object,
				default: {
					deviceState: 0, //连接状态，1.已连接，0.未连接
					deviceName: "", //当前连接的蓝牙名称
					deviceId: "", //当前连接的蓝牙地址
					writeCharaterId: "",
					writeServiceId: "",
					notifyCharaterId: "",
					notifyServiceId: "",
					readCharaterId: "",
					readServiceId: "",
					platform: "",
				}
			},

		},
		created() {
			//初始化
		},
		methods: {
			//设置蓝牙属性
			setBleInfo: function(data) {
				for (let key in data) {
					this.bleInfo[key] = data[key];
				};
				this.$emit('update:bleInfo', this.bleInfo);
			},
			//设置蓝牙连接地址
			setBleData: function(data) {
				for (let key in data) {
					this.bleData[key] = data[key];
				};
			},
			// ------------------------------主动调用
			//搜索设备
			startSearch(fun) {
				try {
					var that = this
					uni.openBluetoothAdapter({
						success: function(res) {
							uni.getBluetoothAdapterState({
								success: function(res) {
									if (res.available) {
										if (res.discovering) {
											uni.stopBluetoothDevicesDiscovery({
												success: function(res) {
													console.log(
														"stopBluetoothDevicesDiscovery success",
														res)
												}
											})
											fun(SUCCESS);
										} else {
											that.getBluetoothDevices(fun);
										}

									} else {
										fun(ERROR("本机蓝牙不可用"));
									}
								},
							})
						},
						fail: function() {
							fun(ERROR("蓝牙初始化失败，请到设置打开蓝牙"));
						}
					})
				} catch (e) {
					fun(ERROR(e.message));
				}

			},
			getBluetoothDevices: function(fun) { //获取蓝牙设备信息
				var that = this
				uni.startBluetoothDevicesDiscovery({
					success: function(res) {
						setTimeout(function() {
							uni.getBluetoothDevices({
								success: function(res) {
									var devices = []
									for (var i = 0; i < res.devices.length; ++i) {
										if (res.devices[i].name != "未知设备") {
											devices.push(res.devices[i]);
										}
									}
									that.deviceListChange(devices);
									uni.stopBluetoothDevicesDiscovery({
										success: function(res) {}
									});
									fun(SUCCESS);
								},
							})
						}, 2000) //搜索2秒后直接返回搜索结果
					},
				})
			},
			//连接设备
			connect(device, fun) {
				var that = this
				uni.stopBluetoothDevicesDiscovery({
					success: function(res) {},
				})
				//操作标识
				that.setBleData({
					serviceId: 0,
					writeCharacter: false,
					readCharacter: false,
					notifyCharacter: false
				})
				uni.createBLEConnection({
					deviceId: device.deviceId,
					success: function(res) {
						that.setBleInfo({
							deviceState: 1,
							deviceName: device.name,
							deviceId: device.deviceId,
						})
						//获取读写通道ID
						that.getSeviceId(fun);
					},
					fail: function(e) {
						console.log(e);
						fun(ERROR("连接失败"));
					},
					complete: function(e) {}
				})
			},
			//更新设备列表
			deviceListChange(deviceList) {
				this.$emit('deviceListChange', deviceList);
			},
			getSeviceId(fun) {
				var that = this
				var platform = this.bleInfo.platform
				wx.getBLEDeviceServices({
					deviceId: that.bleInfo.deviceId,
					success: function(res) {
						// var realId = ''
						// if (platform == 'android') {
						//   // for(var i=0;i<res.services.length;++i){
						//   // var item = res.services[i].uuid
						//   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
						//   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
						//   //       break;
						//   //     }
						//   // }
						// } else if (platform == 'ios') {
						//   // for(var i=0;i<res.services.length;++i){
						//   // var item = res.services[i].uuid
						//   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
						//   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
						//   // break
						//   // }
						//   // }
						// }
						// that.bleInfo.serviceId = realId


						//操作标识
						that.setBleData({
							services: res.services
						})
						that.getCharacteristics(fun)
					},
					fail: function(e) {
						console.log(e);
						fun(ERROR("连接失败"));
					},
					complete: function(e) {}
				})
			},
			getCharacteristics: function(fun) {
				var that = this
				var list = that.bleData.services
				var num = that.bleData.serviceId
				var write = that.bleData.writeCharacter
				var read = that.bleData.readCharacter
				var notify = that.bleData.notifyCharacter
				uni.getBLEDeviceCharacteristics({
					deviceId: that.bleInfo.deviceId,
					serviceId: list[num].uuid,
					success: function(res) {
						for (var i = 0; i < res.characteristics.length; ++i) {
							var properties = res.characteristics[i].properties
							var item = res.characteristics[i].uuid
							if (!notify) {
								if (properties.notify) {
									that.setBleInfo({
										notifyCharaterId: item,
										notifyServiceId: list[num].uuid
									})
									notify = true
								}
							}
							if (!write) {
								if (properties.write) {
									that.setBleInfo({
										writeCharaterId: item,
										writeServiceId: list[num].uuid
									})
									write = true
								}
							}
							if (!read) {
								if (properties.read) {
									that.setBleInfo({
										readCharaterId: item,
										readServiceId: list[num].uuid
									})
									read = true
								}
							}
						}
						if (!write || !notify || !read) {
							num++
							that.setBleData({
								writeCharacter: write,
								readCharacter: read,
								notifyCharacter: notify,
								serviceId: num
							})
							if (num == list.length) {
								wx.showModal({
									title: '提示',
									content: '找不到该读写的特征值',
									showCancel: false
								})
							} else {
								that.getCharacteristics(fun)
							}
						} else {
							if (fun) {
								fun(SUCCESS); //连接成功
							}
						}
					},
					fail: function(e) {
						console.log(e);
						fun(ERROR("连接未知异常")); //未知异常
					},
					complete: function(e) {
						// console.log("write:" + that.bleInfo.writeCharaterId)
						// console.log("read:" + that.bleInfo.readCharaterId)
						// console.log("notify:" + that.bleInfo.notifyCharaterId)
					}
				})
			},


		}
	}
</script>

<style scoped>

</style>
<style lang="scss">

</style>